'use strict';
app.service('shopAnalysisService',['$http','$q','$filter','$cookies','utilService',function($http,$q,$filter,$cookies,utilService){
    //查询店铺分析数据
    this.findShopAnalysis = function($scope){
        var deferred = $q.defer();
        utilService.get({
            url:$scope.app.domain + 'shop/history/analysis',
            params:{
                startTime:$scope.analysis.startTime,
                endTime:$scope.analysis.endTime,
                shopId:$scope.analysis.shopId
            }
        }).then(function(response){
            deferred.resolve(response.data);
        },function(e){
            console.error(e);
            deferred.reject("连接服务器出错");
        });
        return deferred.promise;
    };

    //导出数据
    this.exportData = function($scope){
        $http({
            method:'POST',
            url:$scope.app.domain + 'report/shop/analysis',
            data:{
                startTime:$scope.param.startTime,
                endTime:$scope.param.endTime,
                sessionId:$cookies.sessionId,
                shopId:$scope.param.shopId
            },
            responseType: "blob",
            headers:{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj){
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
                return str.join("&");
            }
        }).success(function(data){
            var blob = new Blob([data], {type: "application/vnd.ms-excel"});
            var fileName ="shopAnalysis"+$scope.param.startTime+'至'+$scope.param.endTime+'.xls';
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.download = fileName;
            a.href = URL.createObjectURL(blob);
            a.click();
        })
    };

    //查询用户数量
    this.querySex =function($scope){
        var deferred = $q.defer();
        utilService.get({
            url:$scope.app.domain + 'shop/history/user/sex',
            params:{
                startTime:$scope.analysis.startTime,
                endTime:$scope.analysis.endTime,
                shopId:$scope.analysis.shopId
            }
        }).then(function(response){
            deferred.resolve(response.data);
        },function(e){
            console.error(e);
            deferred.reject("连接服务器出错");
        });
        return deferred.promise;
    }
    //查找连锁品牌下店铺列表
    this.getShopList=function($scope){
        var deferred=$q.defer();
        utilService.get({
            url:$scope.app.domain+"/shop/get/shop/list"
        }).then(
            function(res){
                deferred.resolve(res.data);
            }, function(e){
                deferred.reject("连接服务器出错");
            }
        );
        return deferred.promise;
    }
}]);